package com.vueblog.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vueblog.po.Type;
import com.vueblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class TypeController {

    private final int pageSize = 5;

    @Autowired
    private TypeService typeService;

    @GetMapping("/getTypes")
    public Object getTypes(@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        JSONObject jsonObject = new JSONObject();
        PageHelper.startPage(pageNum,pageSize);

        List<Type> types = typeService.findAll();
        PageInfo<Type> pageInfo = new PageInfo<Type>(types);
        jsonObject.put("pageInfo",pageInfo);
        return jsonObject;
    }

    @GetMapping("/getAllType")
    public Object getAllType(){
        JSONObject jsonObject = new JSONObject();
        List<Type> types = typeService.findAll();
        jsonObject.put("types",types);
        return jsonObject;
    }

    @PostMapping("/saveType")
    public Object getTypes(@RequestBody Type type){
        JSONObject jsonObject =new JSONObject();
        int i = typeService.saveType(type);
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","保存成功");
        }else {
            jsonObject.put("status",500);
            jsonObject.put("msg","保存失败，类型已存在");
        }
        return jsonObject;
    }

    @PostMapping("/deleteType")
    public Object deleteType(@RequestBody Type type){
        JSONObject jsonObject =new JSONObject();
        int i = typeService.deleteType(type.getId());
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","删除成功");
        }else {
            jsonObject.put("msg","删除失败，发生未知错误");
        }
        return jsonObject;
    }

    @PostMapping("/updateType")
    public Object updateType(@RequestBody Type type){
        JSONObject jsonObject =new JSONObject();
        int i = typeService.updateType(type);
        if (i>0){
            jsonObject.put("status",200);
            jsonObject.put("msg","更新成功");
        }else {
            jsonObject.put("status",500);
            jsonObject.put("msg","更新失败，类型已存在");
        }
        return jsonObject;
    }
}
